package	birdry.font	{
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.text.TextFormat;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.AntiAliasType;
	import flash.utils.Dictionary;
	
	import flash.text.TextRenderer;
	import flash.text.FontStyle;
	import flash.text.TextColorType;
	import flash.text.CSMSettings;
	
	import flash.text.Font;
	
	import birdry.font.FontLoader;
	
	public class FontManager		{
		
		public static const FONT_EMBED:String = "fontEmbed";
		
		private static var _instance:FontManager;
		
		private var _fontLoaderList:Dictionary = new Dictionary();
		
		public function FontManager(singletonEnforcer:SingletonEnforcer)	{
			if (_instance)	throw new Error("인스턴스를 생성할 수 없습니다.");
		}
		
		public static function get getInstance():FontManager		{
			if (FontManager._instance == null)		FontManager._instance = new FontManager(new SingletonEnforcer());
			return FontManager._instance;
		}
		
		public function apply(txt:*, fontUrl:String): FontLoader	{
			var fontLoader:FontLoader = _fontLoaderList[fontUrl] as FontLoader;
			if ( !fontLoader )		fontLoader = loadFont( fontUrl );
			if (fontLoader.fontName == null)	{
				fontLoader.addEventListener(FontLoader.FONT_LOAD_COMPLETE, onComplete);
			}	else		{
				embedFont( txt, fontLoader.fontName );
			}
			function onComplete( e: Event ): void	{
				fontLoader.removeEventListener(FontLoader.FONT_LOAD_COMPLETE, onComplete);
				embedFont( txt, fontLoader.fontName );
			}
			return fontLoader;
		}
		
		public function loadFont( fontUrl:String ): FontLoader	{
			var fontLoader:FontLoader = new FontLoader(fontUrl);
			_fontLoaderList[fontUrl] = fontLoader;
			return fontLoader;
		}
		
		private function embedFont( txt:TextField, fontName:String ): void	{
			txt.defaultTextFormat = new TextFormat(fontName);
			txt.setTextFormat(new TextFormat(fontName));
			txt.antiAliasType = AntiAliasType.NORMAL;
			txt.embedFonts = true;
			txt.dispatchEvent( new Event( FontManager.FONT_EMBED ));
		}
	}	// class
	
	
}	// package

class SingletonEnforcer { }